package com.controller;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import com.entity.AllData;
import com.util.DataSourceUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/page")
public class PageServlet  extends HttpServlet{
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        List<AllData> items = new ArrayList<>();
        String sql = "SELECT DISTINCT cid,tid,title FROM AllData";
        try(Connection conn = DataSourceUtils.getConnection();
            PreparedStatement st = conn.prepareStatement(sql);
            ResultSet rs = st.executeQuery()) {
            while (rs.next()) {
                AllData item = new AllData(rs.getInt("cid"), rs.getInt("tid"), rs.getString("title"));
                items.add(item);
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        List<AllData> items2 = new ArrayList<>();
        String sql2 = "SELECT cid,title,name,content,img,content2 FROM AllData where cid=? AND tid=?";
        try(Connection conn2 = DataSourceUtils.getConnection();
            PreparedStatement st2 = conn2.prepareStatement(sql2)){
            st2.setString(1,req.getParameter("cid"));
            st2.setString(2,req.getParameter("tid"));
            try(ResultSet rs2 = st2.executeQuery()) {
                while (rs2.next()) {
                    AllData item = new AllData();
                    item.setCid(rs2.getInt("cid"));
                    item.setTitle(rs2.getString("title"));
                    item.setName(rs2.getString("name"));
                    item.setContent(rs2.getString("content"));
                    item.setContent2(rs2.getString("content2"));
                    item.setImg(rs2.getString("img"));
                    items2.add(item);
                }
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        req.setAttribute("cid",req.getParameter("cid"));
        req.setAttribute("items2", items2);
        req.setAttribute("items", items);
        req.getRequestDispatcher("/WEB-INF/jsp/page.jsp")
                .forward(req, resp);
    }
}
